package com.lwl.office.webeditor.style;

import cn.hutool.core.util.StrUtil;
import com.lwl.office.webeditor.tools.ConvertUtil;
import lombok.Data;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.math.BigInteger;
import java.util.Map;

@Data
public class PStyle extends Style {
    //首行缩进
    private Boolean textIndent;
    //居中
    private String textAlign;
    //对应段前距离
    private String marginTop;
    //断后距离
    private String marginBottom;
    //行高
    private String lineHeight;
    /**
     * 设置样式
     * @param style
     * @return
     */
    public PStyle of(String style){
        Map<String, String> styleMap = parseStyle(style);
        if(styleMap.containsKey("text-align")){
            textAlign = styleMap.get("text-align");
        }
        if(styleMap.containsKey("text-indent")){
            textIndent = styleMap.containsKey("text-indent");
        }
        if(styleMap.containsKey("margin-top")){
            marginTop = styleMap.get("margin-top");
        }
        if(styleMap.containsKey("margin-bottom")){
            marginBottom = styleMap.get("margin-bottom");
        }
        if(styleMap.containsKey("line-height")){
            lineHeight = styleMap.get("line-height");
        }
        return this;
    }

    /**
     * 渲染段落样式
     * @param paragraph
     */
    public void rendParagraph(XWPFParagraph paragraph){
        CTP ctp = paragraph.getCTP();
        CTPPr ppr = ctp.addNewPPr();
        //首行缩进
        if(textIndent!=null && textIndent){
            CTInd ctInd = ppr.isSetInd()?ppr.getInd():ppr.addNewInd();
            ctInd.setLeftChars(BigInteger.valueOf(100));
            ctInd.setLeft(210);
        }
        //对齐方式
        if(StrUtil.isNotEmpty(textAlign)){
            if(textAlign.equals("right")){
                ppr.addNewJc().setVal(STJc.RIGHT);
            }else if( textAlign.equals("center")){
                ppr.addNewJc().setVal(STJc.CENTER);
            }else{
                ppr.addNewJc().setVal(STJc.LEFT);
            }
        }
        //行高
        if(StrUtil.isNotEmpty(lineHeight)){
            CTSpacing ctSpacing = ppr.isSetSpacing()?ppr.getSpacing():ppr.addNewSpacing();
            ctSpacing.setLine(ConvertUtil.html2WordLineHeight(lineHeight));
            ctSpacing.setLineRule(STLineSpacingRule.AUTO);
        }
        //段前
        if(StrUtil.isNotEmpty(marginTop)){
            CTSpacing ctSpacing = ppr.isSetSpacing()?ppr.getSpacing():ppr.addNewSpacing();
            ctSpacing.setBefore(240);
        }
        //段后
        if(StrUtil.isNotEmpty(marginBottom)){
            CTSpacing ctSpacing = ppr.isSetSpacing()?ppr.getSpacing():ppr.addNewSpacing();
            ctSpacing.setAfter(240);
        }
    }
}
